<?php
/**
 * DataController
 * 
 * @author 
 * @version 
 */

require_once 'Zend/Db/Table.php';
require_once 'Zend/Feed/Builder.php';
require_once 'Events.php';
require_once 'Zend/Controller/Action.php';
require_once 'Zend/Dojo.php';

class DataController extends Zend_Controller_Action {
	
	/**
	 * @var Events
	 */
	private $events;
	
	/**
	 * @see Zend_Controller_Action::init()
	 *
	 */
	public function init() {
		parent::init ();
		
		$this->events = new Events ( );
		Zend_Dojo::enableView ( $this->view );
		
		$delay = $this->getRequest ()->getParam ( 'delay' );
		if (! empty ( $delay )) {
			usleep ( $delay * 1000 );
		}
	}
	
	/**
	 * add action
	 */
	public function insertAction() {
		$data = $this->getCurrentRowContent ();
		$row = $this->getTable ()->createRow ( $data );
		if (! $row) {
			$this->_forward ( 'error', null, null, array ('message' => "failed to perform addition $row->toArray()" ) );
			return;
		}
		$row->save ();
		$this->_helper->dojojson ( $row->toArray () );
	}
	
	/**
	 * delete action
	 */
	public function deleteAction() {
		$data = $this->getCurrentRowContent ();
		$rows = $this->getTable ()->find ( $data ['id'] );
		if (! $rows || count ( $rows ) == 0) {
			$this->_forward ( 'error', null, null, array ('message' => "failed to perform addition $data" ) );
			return;
		}
		$row = $rows->current ();
		$row->delete ();
		$this->_helper->dojojson ( array_values ( $row->toArray () ) );
	}
	
	/**
	 * update action
	 */
	public function updateAction() {
	
		$data = $this->getCurrentRowContent ();
		$rows = $this->getTable ()->find ( $data ['id'] );
		if (! $rows || count ( $rows ) == 0) {
			$this->_forward ( 'error', null, null, array ('message' => "failed to perform addition $rows->toArray()" ) );
			return;
		}
		$row = $rows->current ();
		foreach ( $data as $key => $value ) {
			if ($row->$key != $value) {
				$row->$key = $value;
			}
		}
		$row->save ();
		$this->_helper->dojojson ( array_values ( $row->toArray () ) );
	}
	
	public function getCurrentRowContent() {
		return $this->getContent ( '_' );
	}
	
	public function getContent($prefix) {
		$columns = $this->getColumns ();
		$i = 0;
		$result = array ();
		foreach ( $columns as $col ) {
			$value = $this->getRequest ()->getParam ( $prefix . $i );
			if ($value) {
				$result [$col->Field] = ( string ) $value;
			}
			$i ++;
		}
		return $result;
	}
	
	/**
	 * select action
	 */
	public function selectAction() {
		
		// creates the select statement
		$statement = $this->events->select ();
		
		// finds an initial where filtering
		$messages = $this->_helper->flashMessenger->getMessages ();
		if (count ( $messages ) > 0) {
			$where = $messages [0];
			$statement->where ( $where )->limit ( 1 );
		} else {
			// retreive params
			$params = $this->getRequest ()->getParams ();
			
			// pagination
			$lim = $this->getRequest ()->getParam ( 'limit' );
			$off = $this->getRequest ()->getParam ( 'offset' );
			if ($lim || $off) {
				$statement->limit ( $lim, $off );
			}
			
			// order by
			$desc = ( boolean ) $this->getRequest ()->getParam ( 'desc' );
			if (is_numeric ( $this->getRequest ()->getParam ( 'orderby' ) )) {
				$columns = $this->getColumns ();
				$ob = $columns [intval ( $this->getRequest ()->getParam ( 'orderby' ) ) - 1]->Field;
				$statement->order ( $ob . ($desc ? " DESC" : "") );
			}
			
			// additional where
			$where = $this->getRequest ()->getParam ( 'where' );
			if ($where) {
				$statement->where ( $where );
			}
			
			// execute
			$all = $statement->query ()->fetchAll ();
			if (! $all) {
				$this->_forward ( 'error', null, null, array ('message' => "failed to perform query $statement->assemble()" ) );
				return;
			}
			
			$result = array ();
			foreach ( $all as $col ) {
				$result [] = array_values ( $col );
			}
			
			// json results
			$this->_helper->dojojson ( $result );
		}
	}
	
	/**
	 * error handling action
	 */
	public function errorAction() {
		$exception = $this->_helper->flashMessenger->getMessages ();
		$message = str_replace ( '"', '\\"', empty ( $exception ) ? '' : $exception [0] );
		$this->_helper->dojojson ( array ('error' => true, 'message' => $message ) );
	}
	
	/**
	 * information about this controller / database
	 */
	public function infoAction() {
		try {
			$rowCount = $this->rowCount ();
			$cols = $this->getColumns ();
			$this->_helper->dojojson ( array ('count' => $rowCount, 'columns' => $cols ) );
		} catch ( Exception $e ) {
			$this->_helper->flashMessenger ( 'error: ' . $e->getMessage () );
			$this->_forward ( 'error' );
		}
	}
	
	public function columnsAction() {
		$this->_helper->dojojson ( $this->getColumns () );
	}
	
	/**
	 * This action handles the number of rows 
	 */
	public function rowcountAction() {
		$this->_helper->dojojson ( $this->rowcount () );
	}
	
	/**
	 * @return array names of the table's columns
	 */
	function getColumns() {
		$metadata = $this->getTable ()->info ( Zend_Db_Table::METADATA );
		$result = array ();
		foreach ( $metadata as $colInfo ) {
			$col = new stdClass ( );
			$col->Field = $colInfo ['COLUMN_NAME'];
			$col->Type = $colInfo ['DATA_TYPE'];
			$col->Null = (( boolean ) $colInfo ['NULLABLE']) ? 'YES' : 'NO';
			$col->Key = (( boolean ) $colInfo ['PRIMARY']) ? 'PRI' : '';
			$col->Default = $colInfo ['DEFAULT'];
			$col->Extra = "";
			$result [] = $col;
		}
		return $result;
	}
	
	/**
	 * @return int the number of rows in the table
	 */
	function rowcount() {
		return $this->getTable ()->fetchAll ()->count ();
	}
	
	/**
	 * @return Zend_Db_Table_Abstract
	 */
	function getTable() {
		return $this->events;
	}
	
	public function rssAction() {
		$allRows = $this->getTable ()->fetchAll ()->toArray();

		$items = array();
		foreach ($allRows as $row) {
			$item = array(
                 'title'        => $row['start'] . " - " . $row['title'], //required
                 'link'         => empty($row['link']) ? "none" : $row['link'], //required
                 'description'  => empty($row['description']) ? "none" : $row['description'], // only text, no html, required
			);
			$items[] = $item;
		}
		
		$array = array ('title' => 'Timeline atom', //required
				'link' => 'http://dashboard.zend.net', //required
				'charset' => 'UTF-8', // required
				'entries' => $items );
		$atom = Zend_Feed::importArray ( $array , 'rss');
		$atom->saveXml();
		$atom->send();
		die(0);
	}
}
?>

